import {messages, queryCurrencyPrecision, currencyPrecisionCal, deepFullCopy} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import config from 'config'
import { Form, Button, Spin, InputNumber, Modal, Checkbox, Row, Col, Select, Popover, Icon, Table, Popconfirm, message, Tag, Input } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
import Chooser from 'components/chooser'
import chooserData from 'share/chooserData'

import moment from 'moment'
import baseService from 'share/base.service'
import requestService from 'containers/request/request.service'
import ExpenseTypeSelector from 'components/template/expense-type-selector'
import 'styles/request/new-request/expense-type-modal.scss'
import configureStore from 'stores'

class ExpenseTypeModal extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      value: {},
      modalVisible: false,
      uneditable: false, //是否不可编辑费用类型，支付方式，币种，金额
      currencyFetching: false,
      rowIndex: undefined,
      currencyOptions: [],
      expenseChosenInfo: {}, //选中的费用类型信息
      canSubmit: false, //是否可以提交
      isHidePaymentType: false, //是否隐藏支付方式
      paymentType: 1001, //支付方式：1001（个人支付）、1002（公司支付）
      currencyCode: props.company.baseCurrency, //币种
      isDisableCurrency: false, //是否禁用选择币种
      tableLoading: false, //切换部门调接口是否清空成本中心项的时候loading用
      departmentOID: '', //如果表单配了部门控件且有值，则为表单部门控件的值，否在为单据岗位所在的部门的值
      companyOID: props.company.companyOID, //如果表单配了公司控件且有值，则为表单公司控件的值，否在为单据岗位所在的公司的值
      componentCompanyOID: '', //单据控件的companyOID
      amount: null, //金额
      reimbursementTypeField: null, //报销类型控件
      remark: '', //备注字段
      remarkPlaceholder: '',
      remarkTypes: ['MCD1014','MCD1015','MCD1019','MCD1020','MCD1022','MCD1025','MCD1026'],
      actualCurrencyRate: 1, //汇率
      companyCurrencyRate: 1, //企业汇率
      rateDeviation: 0.00, //汇率偏移
      expenseBudgetList: [],
      deletedBudgetOIDList: [], //标记页面上手动删除过的预算明细
      columns: [
        {title: '', dataIndex: 'id', width: '5%', render: (value, record) => <img src={record.expenseType.iconURL} style={{width:20, maxHeight: 20}}/>},
        {title: messages('request.key224'/*费用类型*/), dataIndex: 'expenseType', render: value => {
          return value.name ? <Popover content={value.name}>{value.name}</Popover> : <span style={{color: '#FF0000'}}>{messages('request.key561')/*请选择类型*/}</span>;
        }},
        {title: messages('request.key225'/*币种*/), dataIndex: 'currencyCode', width: '8%'},
        {title: messages('request.key226'/*金额*/), dataIndex: 'amount', render: (value, record)=>{
          return value ? this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)) : <span className="money-cell" style={{color: '#FF0000'}}>{messages('request.key558')/*请填写金额*/}</span>;
        }},
        {title: messages('request.key227'/*汇率*/), dataIndex: 'actualCurrencyRate', render: value => this.filterMoney(value || 1, 2)},
        {title: messages('request.key230'/*本币金额*/), dataIndex: 'baseCurrencyAmount',
          render: (value, record)=>this.filterMoney(value, queryCurrencyPrecision(props.formDetail.currencyCode || props.company.baseCurrency))},
        {title: messages('request.key231'/*支付方式*/), dataIndex: 'paymentType', render: value =>
          Number(value) === 1001 ? messages('request.key232'/*个人支付*/) : messages('request.key233'/*公司支付*/)},
        {title: messages('common.remark')/*备注*/, dataIndex: 'remark', width: '15%', render: value => {
          return value ? <Popover content={value}>{value}</Popover> : null
        }},
        {title: messages('common.operation'), dataIndex: 'expenseTypeOID', width: '7%', render: (value, record, index) => {
          return !!record.uneditable ? "--" : (
            <Popconfirm title={messages('common.confirm.delete')} onConfirm={(e) => this.deleteExpenseType(e, index)}>
              <a onClick={(e) => {e.stopPropagation()}}>{messages('common.delete')}</a>
            </Popconfirm>
          )
        }}
      ],
      warnExchangeRateTol: 10, //汇率容差警告值
      prohibitExchangeRateTol: 20, //汇率容差最大值
      applicationOID: null, //申请人OID
      baseCurrency: null, //申请人的本位币
      isShowSelectExpense: true, //是否展示费用类型选择
      //预算明细上分摊相关的变量定义
      expenseApportionColumns: [],
      isHasApportion: false, //费用上是否有分摊
      apportionTemplate: {
        entityType: 1001,
        scale: 0,
        amount: 0,
        defaultApportion : false,
        costCenterItems: []
      },//新增一行费用分摊的模板, 也就是非默认分摊的模板
      defaultApportion: {
        entityType: 1001,
        scale: 100,
        amount: 0,
        defaultApportion : true,
        costCenterItems: []
      },//默认分摊的模板，初始化的时候用
      apportionList: []    //费用分摊列表
    }
  }

  componentDidMount() {
    const {columns} = this.state;
    this.setState({
      value: this.props.value || {},
      expenseBudgetList: (this.props.value || {}).budgetDetail || [],
      baseCurrency: this.props.company.baseCurrency
    })
    if (false && this.props.formDetail.formType === 2001) {
      let itineraryInfo = {
        title: messages('request.key559')/*行程*/,
        width: '15%',
        dataIndex: 'itineraryOID',
        render: (value, record) => {
          return this.renderItineraryStr(record, true);
        }
      };
      columns.splice(2, 0, itineraryInfo);
      this.setState({columns});
    }
  }

  renderItineraryStr = (record, isNeedPopover) => {
    let itineraryStr = '';
    let summary = record.itinerarySummary ? JSON.parse(record.itinerarySummary) : null;
    if (record.itineraryType === 1001 || record.itineraryType === 1002) {
      itineraryStr = record.itineraryType === 1001 ? messages('request.key560')/*飞机*/ : messages('request.key410')/*火车*/;
      let fromCityStr = summary.fromCity ? summary.fromCity : messages('request.key490')/*不限*/;
      let toCityStr = summary.toCity ? summary.toCity : messages('request.key490')/*不限*/;
      itineraryStr = summary ? `${itineraryStr} | ${summary.startDate} | ${fromCityStr} - ${toCityStr}` : '-';
    }
    if (record.itineraryType === 1003) {
      itineraryStr = messages('request.key414')/*酒店*/;
      let cityStr = summary.city ? summary.city : messages('request.key490')/*不限*/;
      itineraryStr = summary ? `${itineraryStr} | ${summary.startDate} | ${cityStr}` : '-';
    }
    if (record.itineraryType === 1006) {
      let cityStr = summary.toCity ? summary.toCity : messages('request.key555')/*通用城市*/;
      itineraryStr = messages('request.key413')/*差补*/;
      itineraryStr = summary ? `${itineraryStr} | ${summary.startDate} ~ ${summary.endDate} | ${cityStr}` : '-';
    }
    return itineraryStr ? (isNeedPopover ? <Popover content={itineraryStr}>{itineraryStr}</Popover> : itineraryStr) : '--';
  };

  componentWillReceiveProps(nextProps) {
    if (this.state.baseCurrency && nextProps.company.baseCurrency !== this.state.baseCurrency) {
      this.setState({ baseCurrency: nextProps.company.baseCurrency },() => {
        if (this.state.expenseBudgetList.length && this.props.formDetail.currencyCode !== this.state.baseCurrency) {
          message.info(messages('request.key234'/*申请人本位币变化，已清除添加的预算明细*/));
          this.setState({ value: {}, expenseBudgetList: [] });
          this.onChange(null)
        }
      })
    }
    //表单values set为undefined，控件上的value没有变化，要进行清空
    if (!nextProps.value && this.state.expenseBudgetList.length) {
      this.setState({ value: {}, expenseBudgetList: [] });
    }
    if (nextProps.value) {
      let budgetDetail = nextProps.value.budgetDetail ? nextProps.value.budgetDetail : [];
      let deletedBudgetOIDList = nextProps.value.deletedBudgetOIDList ? nextProps.value.deletedBudgetOIDList : [];
      this.setState({ deletedBudgetOIDList, expenseBudgetList: budgetDetail }, () => {
        this.initApportion(nextProps);
      });
    } else {
      this.initApportion(nextProps);
    }
  };

  initApportion = (nextProps) => {
    let refreshAmount = false;//是否重新计算金额
    if (nextProps.value && nextProps.value.refreshAmount) {
      refreshAmount = true;
    }
    if (nextProps.copyValue && nextProps.copyValue.length) {
      this.initExpenseApportionColumns(nextProps.jobInfo);
      this.initPaymentType(nextProps.copyValue);
      this.initCompanyOID(nextProps.copyValue, refreshAmount, nextProps.jobInfo);
      this.initApportionTemplate(nextProps.copyValue);
      this.initDepartmentOID(nextProps.copyValue, nextProps.jobInfo);
    }
  };

  //处理预算明细上分摊相关的变量定义
  initExpenseApportionColumns = (jobInfo) => {
    const { user } = this.props;
    let expenseApportionColumns = [
      {title: messages('request.key516')/*分摊项*/, dataIndex: 'costCenterItems', render: (value, record, tableIndex) => {
        let lineDepartmentOID = ''; //分摊行上部门
        value && value.map(item => {
          if (item.type === 1) {
            lineDepartmentOID = item.costCenterOID;
          }
        });
        return (
          <div>
            {record.budgetLabelCode === 'BUD_002' && <Tag color="red">{messages('request.key297')/*超预算*/}</Tag>}
            {record.budgetLabelCode === 'BUD_003' && <Tag color="blue">{messages('request.key550')/*预算预警*/}</Tag>}
            {
              value.map((oneApportion, index) => {
                let chooserItem = null;
                let leafEnable = !React.Component.prototype.checkFunctionProfiles('department.leaf.selection.required', [undefined, false]);
                //部门
                if (oneApportion.type === 1) {
                  chooserItem = deepFullCopy(chooserData['department']);
                  chooserItem.url += `?leafEnable=${leafEnable}`;
                  if (React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [true])) {
                    oneApportion.value = oneApportion.name ? [{name: oneApportion.name, departmentOid: oneApportion.costCenterOID}] : undefined;
                  } else {
                    oneApportion.value = oneApportion.name ? [{path: oneApportion.name, departmentOid: oneApportion.costCenterOID}] : undefined;
                  }
                  chooserItem.columns.map(item => {
                    if (item.dataIndex === 'name') {
                      item.render = (value, record) => {
                        let departmentOID = jobInfo.departmentOID;
                        let message = '';
                        if ((!departmentOID && user.departmentOID === record.departmentOid) || (departmentOID && departmentOID === record.departmentOid)) {
                          message = messages('components.key696')/*(我的)*/;
                        }
                        if(React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [undefined, false])){
                          return (
                            <Popover
                              placement="topLeft"
                              overlayStyle={{ maxWidth: 500 }}
                              content={`${message}${record.path}`}>
                              {message}{record.path}
                            </Popover>
                          );
                        }
                        return (
                          <Popover
                            placement="topLeft"
                            content={`${message}${record.name}`}>
                            {message}{record.name}
                          </Popover>
                        );
                      };
                    }
                  });
                }
                //成本中心
                if (oneApportion.type === 0) {
                  chooserItem = deepFullCopy(chooserData['cost_center_item']);
                  chooserItem.url = `${config.baseUrl}/api/my/cost/center/items`;
                  oneApportion.value = oneApportion.name ? [{name: oneApportion.name, costCenterItemOID: oneApportion.costCenterOID}] : undefined;
                }
                return oneApportion.isApportionItem ? (
                  <div key={index}>
                    {oneApportion.type === 1 && (
                      <Row type="flex" align="middle" style={{marginBottom: 5}}>
                        <Col span={4} className="expense-apportion-name">
                          <Popover content={oneApportion.fieldName}><span className="required">*</span>{oneApportion.fieldName}</Popover>
                        </Col>
                        <Col span={20} className="expense-apportion-chooser">
                          <Chooser
                            selectorItem={chooserItem}
                            valueKey="departmentOid"
                            labelKey={React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [true]) ? 'name' : 'path'}
                            onlyNeed="departmentOid"
                            listExtraParams={{companyOID: this.state.companyOID}}
                            value={oneApportion.value}
                            onChange={(e, all) => {
                              this.checkedChange(e, all, tableIndex, oneApportion.type)
                            }}
                            single
                          />
                        </Col>
                      </Row>
                    )}
                    {oneApportion.type === 0 && (
                      <Row type="flex" align="middle" style={{marginBottom: 5}}>
                        <Col span={4} className="expense-apportion-name">
                          <Popover content={oneApportion.fieldName}>
                            {oneApportion.required && <span className="required">*</span>}{oneApportion.fieldName}
                          </Popover>
                        </Col>
                        <Col span={20} className="expense-apportion-chooser">
                          <Chooser
                            selectorItem={chooserItem}
                            valueKey="costCenterItemOID"
                            labelKey="name"
                            onlyNeed="costCenterItemOID"
                            listExtraParams={{
                              costCenterOID: oneApportion.costCenter,
                              userOID: user.userOID,
                              companyOID: this.state.companyOID,
                              departmentOID: lineDepartmentOID || this.state.departmentOID,
                              expenseTypeOID: (this.state.expenseChosenInfo.expenseType && this.state.expenseChosenInfo.expenseType.expenseTypeOID) || this.state.expenseChosenInfo.expenseTypeOID,
                              parentCostCenterItemOID: oneApportion.costCenterType === 'son' ? oneApportion.parentCostCenterOID : undefined
                            }}
                            value={oneApportion.value}
                            disabled={oneApportion.costCenterType === 'son' && !oneApportion.parentCostCenterOID}
                            onChange={(e, all) => {
                              this.checkedChange(e, all, tableIndex, oneApportion.type, oneApportion.costCenter)
                            }}
                            single
                          />
                        </Col>
                      </Row>
                    )}
                  </div>
                ) : (<div />)
              })
            }
          </div>
        );
      }},
      {title: messages('request.key517')/*分摊金额*/, dataIndex: 'amount', width: '15%', render: (value, record, tableIndex) => {
        return (
          <InputNumber size="small"
                       min={0}
                       precision={queryCurrencyPrecision(this.state.currencyCode)}
                       step={1}
                       disabled={tableIndex === 0}
                       value={value}
                       onChange={(num) => {this.handleChangeAmountOrScale(num, 'amount', tableIndex)}}
                       placeholder={messages('common.please.enter')}
                       style={{width:'100%'}}/>
        )
      }},
      {title: messages('request.key518')/*分摊比例%*/, dataIndex: 'scale', width: '15%', render: (value, record, tableIndex) => {
        return (
          <InputNumber size="small"
                       min={0}
                       precision={2}
                       step={1}
                       disabled={tableIndex === 0}
                       value={value}
                       onChange={(num) => {this.handleChangeAmountOrScale(num, 'scale', tableIndex)}}
                       placeholder={messages('common.please.enter')}
                       style={{width:'100%'}}/>
        )
      }},
      {title: messages('request.key309')/*操作*/, dataIndex: 'index', width: '15%', render: (value, record, tableIndex) => {
        return (
          <span>
            <a onClick={(e) => {e.stopPropagation(); this.copyApportion(tableIndex);}}>{messages('common.copy')}</a>&nbsp;&nbsp;&nbsp;
            {tableIndex !== 0 && (
              <a onClick={(e) => {e.stopPropagation(); this.deleteApportion(tableIndex);}}>{messages('common.delete')}</a>
            )}
          </span>
        )
      }}
    ];
    this.setState({expenseApportionColumns});
  };

  //处理支付方式是否显示
  initPaymentType = (customValues) => {
    const { columns } = this.state;
    let isHidePaymentType = false;
    customValues.map(customValue => {
      if (customValue.messageKey === 'budget_detail' && customValue.fieldContent) {
        isHidePaymentType = JSON.parse(customValue.fieldContent).hideCompanyPay;
      }
    });
    this.setState({isHidePaymentType});
    if (isHidePaymentType) {
      let spliceIndex = -1;
      columns.map((column, index) => {
        if (column.dataIndex === 'paymentType') {
          spliceIndex = index;
        }
      });
      if (spliceIndex > -1) {
        columns.splice(spliceIndex, 1);
        this.setState({columns});
      }
    }
  };

  //编辑预算明细的时候才会有传进来的recordCurrencyCode
  initCurrency = (customValues, recordCurrencyCode) => {
    let currencyCode = null;
    customValues.map(customValue => {
      if (customValue.messageKey === 'currency_code' && customValue.value) {
        currencyCode = customValue.value;
      }
    });
    if (currencyCode) {
      this.setState({
        isDisableCurrency: true,
        currencyCode: recordCurrencyCode ? recordCurrencyCode : currencyCode
      }, () => {
        //只有新建预算明细的时候才需要重新获取汇率
        if (currencyCode !== this.props.company.currencyCode && !recordCurrencyCode) {
          this.getRate();
        }
      });
    } else {
      this.setState({
        isDisableCurrency: false
      });
    }
  };

  //初始化要传入成本中心控件的公司oid
  //refreshAmount是否重新计算预算金额
  initCompanyOID = (customValues, refreshAmount, jobInfo) => {
    const { company } = this.props;
    const { companyOID: currentCompanyOID, componentCompanyOID } = this.state;
    let isHasCompany = false; //表单是否配置了公司控件
    let companyOID = ''; //公司控件上的companyOID
    let entityCompanyOID = (jobInfo && jobInfo.companyOID) || company.companyOID;  //单据的companyOID
    customValues.map(customValue => {
      if (customValue.messageKey === 'select_company') {
        isHasCompany = true;
        companyOID = customValue.value;
      }
    });
    let isChangeCompany = isHasCompany && companyOID !== componentCompanyOID;
    this.setState({companyOID: companyOID || entityCompanyOID, componentCompanyOID: companyOID}, () => {
      this.initDefaultApportion(customValues, isChangeCompany, refreshAmount);
    });
  };

  //初始化单据部门oid
  initDepartmentOID = (customValues, jobInfo) => {
    let departmentOID = jobInfo && jobInfo.departmentOID;
    customValues.map(customValue => {
      if (customValue.messageKey === 'select_department' && customValue.value) {
        departmentOID = customValue.value;
      }
    });
    this.setState({departmentOID});
  };

  //初始化分摊模板
  initApportionTemplate = (customValues) => {
    const {apportionTemplate} = this.state;
    let isHasDepartment = false; //表单是否配置了部门控件
    //先清空模板数据
    apportionTemplate.costCenterItems = [];
    let departmentCostCenterItem = {};
    customValues.map(customValue => {
      let costCenterItem = {};
      //处理部门
      if (customValue.messageKey === 'select_department') {
        isHasDepartment = true;
        costCenterItem.type = 1;
        costCenterItem.fieldName = customValue.fieldName;
        costCenterItem.isApportionItem = customValue.fieldConstraint ? JSON.parse(customValue.fieldConstraint).isApportionItem : false;
        costCenterItem.name = '';
        costCenterItem.costCenter = '00000000-0000-0000-0000-000000000000';
        costCenterItem.costCenterOID = '';    //部门oid
        departmentCostCenterItem = JSON.parse(JSON.stringify(costCenterItem));
      }
      //处理成本中心
      if (customValue.messageKey === 'select_cost_center') {
        costCenterItem.type = 0;
        costCenterItem.fieldName = customValue.fieldName;
        costCenterItem.isApportionItem = customValue.fieldConstraint ? JSON.parse(customValue.fieldConstraint).isApportionItem : false;
        costCenterItem.name = '';
        costCenterItem.costCenterOID = '';    //成本中心项oid
        costCenterItem.required = customValue.required;
        if (customValue.dataSource) {
          let tmp = JSON.parse(customValue.dataSource);
          //配得有问题的成本中心不塞入费用分摊中
          if (tmp.type) {
            costCenterItem.costCenterType = tmp.type;
          }
          costCenterItem.costCenter = tmp.costCenterOID;
          apportionTemplate.costCenterItems.push(costCenterItem);
        }
      }
    });
    //如果没有配置部门也要塞入一个部门控件
    if (!isHasDepartment) {
      departmentCostCenterItem = {
        type: 1,
        fieldName: messages('request.key4')/*部门*/,
        isApportionItem: true,
        name: '',
        costCenter: '00000000-0000-0000-0000-000000000000',
        costCenterOID: ''
      };
    }
    apportionTemplate.costCenterItems.splice(0, 0, departmentCostCenterItem);//部门放在第一个
    this.setState({apportionTemplate});
  };

  //初始化默认分摊
  initDefaultApportion = (customValues, isChangeCompany, refreshAmount) => {
    const {apportionList} = this.state;
    let defaultApportion = {
      entityType: 1001,
      scale: 100,
      amount: 0,
      defaultApportion : true,
      costCenterItems: []
    };
    let isHasDepartment = false; //表单是否配置了部门控件
    let parentCostCenterOID = '';//父成本中心项oid
    let departmentCostCenterItem = {};
    customValues.map(customValue => {
      let costCenterItem = {};
      //处理部门
      if (customValue.messageKey === 'select_department') {
        isHasDepartment = true;
        costCenterItem.type = 1;
        costCenterItem.fieldName = customValue.fieldName;
        costCenterItem.isApportionItem = customValue.fieldConstraint ? JSON.parse(customValue.fieldConstraint).isApportionItem : false;
        costCenterItem.name = '';
        costCenterItem.costCenter = '00000000-0000-0000-0000-000000000000';
        if (customValue.showName && (customValue.showName.name || customValue.showName.path)) {
          costCenterItem.name = React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [true]) ? customValue.showName.name : (
              customValue.showName.path ? customValue.showName.path : customValue.showName.name
          );
          costCenterItem.pathDepth = customValue.showName.path ? customValue.showName.path.split('|').length : 1;
          costCenterItem.costCenterOID = customValue.value;//部门oid
        }
        departmentCostCenterItem = JSON.parse(JSON.stringify(costCenterItem));
      }
      //处理成本中心
      if (customValue.messageKey === 'select_cost_center') {
        costCenterItem.type = 0;
        costCenterItem.fieldName = customValue.fieldName;
        costCenterItem.isApportionItem = customValue.fieldConstraint ? JSON.parse(customValue.fieldConstraint).isApportionItem : false;
        costCenterItem.name = '';
        costCenterItem.costCenterOID = '';    //成本中心项oid
        costCenterItem.required = customValue.required;
        if (customValue.dataSource) {
          let tmp = JSON.parse(customValue.dataSource);
          //配得有问题的成本中心不塞入费用分摊中
          if (tmp.type) {
            costCenterItem.costCenterType = tmp.type;
            if (tmp.type === 'father' && customValue.value) {
              parentCostCenterOID = customValue.value;
            }
            //子成本中心在父成本中心之后，此时parentCostCenterOID已赋值
            if (tmp.type === 'son' && parentCostCenterOID) {
              costCenterItem.parentCostCenterOID = parentCostCenterOID;
            }
          }
          costCenterItem.costCenter = tmp.costCenterOID;
          costCenterItem.costCenterOID = customValue.value ? customValue.value : '';
          costCenterItem.name = customValue.showName && customValue.showName.name ? customValue.showName.name : '';
          defaultApportion.costCenterItems.push(costCenterItem);
        }
      }
    });
    //如果没有配置部门也要塞入一个部门控件
    if (!isHasDepartment) {
      let departName = '';
      let pathDepth = 1;
      if (this.props.profile && this.props.profile['department.full.path.disabled'] && this.props.user.departmentName) {
        let array = this.props.user.departmentName.split('|');
        departName = array[array.length - 1];
        pathDepth = array.length;
      } else {
        departName = this.props.user.departmentName;
      }
      departmentCostCenterItem = {
        type: 1,
        fieldName: messages('request.key4')/*部门*/,
        isApportionItem: true,
        name: departName,
        pathDepth: pathDepth,
        costCenter: '00000000-0000-0000-0000-000000000000',
        costCenterOID: this.props.user.departmentOID
      };
    }
    defaultApportion.costCenterItems.splice(0, 0, departmentCostCenterItem);//部门放在第一个
    if (this.judgeDefaultApportionChange(JSON.parse(JSON.stringify(defaultApportion)), this.state.defaultApportion)) {
      apportionList[0] = JSON.parse(JSON.stringify(defaultApportion));
      //let isRefreshList = false;
      //如果保存后进编辑页此时this.state.defaultApportion.costCenterItems这个是没有，此时只用更新默认分摊模版，但不用刷一遍默认分摊数据
      // if (defaultApportion.costCenterItems.length === this.state.defaultApportion.costCenterItems.length) {
      //   isRefreshList = true;
      // }
      this.setState({apportionList, defaultApportion}, () => {
        if (refreshAmount) {
          this.refreshBudgetList(isChangeCompany, refreshAmount);
        }
      });
    } else {
      //如果默认分摊没有变化，但是isChangeCompany为true，需要清空成本中心项。这种情况出现在默认分摊的成本中心项本来就是空的时候。
      //isChangeCompany为true不需要清空分摊行上的成本中心项
      // if (isChangeCompany) {
      //   this.refreshBudgetList(isChangeCompany);
      // }
      //金额的重新计算，以及把开启了分摊但没有默认分摊的费用赋值默认分摊
      if (refreshAmount) {
        this.refreshBudgetList(false, true);
      }
    }
  };

  //校验默认分摊是否变了
  judgeDefaultApportionChange = (newDefaultApportion, oldDefaultApportion) => {
    let isChange = false;
    let oldOIDStrTag = '';
    oldDefaultApportion.costCenterItems && oldDefaultApportion.costCenterItems.map(costCenterItem => {
      oldOIDStrTag += costCenterItem.costCenterOID;
    });
    let newOIDStrTag = '';
    newDefaultApportion.costCenterItems && newDefaultApportion.costCenterItems.map(costCenterItem => {
      newOIDStrTag += costCenterItem.costCenterOID;
    });
    if (newOIDStrTag !== oldOIDStrTag) {
      isChange = true;
    }
    return isChange;
  };

  //默认分摊变了，不需要把所有预算明细上带分摊的默认分摊都修改一下了，和差旅一致，只有新建的费用的默认分摊是最新的，其他的是之前选的啥就是啥
  refreshBudgetList = (isChangeCompany, refreshAmount) => {
    const { formDetail, company } = this.props;
    let { value, expenseBudgetList, defaultApportion } = this.state;
    let isChange = false;
    if (expenseBudgetList.length) {
      expenseBudgetList.map(expense => {
        //refreshAmount只对行程生成的自动预算开分摊了但没默认分摊的做处理，已有默认分摊的费用不做处理
        // if (expense.apportionmentDTOList && expense.apportionmentDTOList.length && !refreshAmount) {
        //   if (this.judgeDefaultApportionChange(defaultApportion, expense.apportionmentDTOList[0])) {
        //     isChange = true;
        //     expense.apportionmentDTOList[0].costCenterItems = JSON.parse(JSON.stringify(defaultApportion.costCenterItems));
        //   }
        //   if (isChangeCompany) {
        //     expense.apportionmentDTOList.map((apportionmentDTO, index) => {
        //       if (index !== 0) {
        //         isChange = true;
        //         apportionmentDTO.costCenterItems.map(costCenterItem => {
        //           if (costCenterItem.type === 0) {
        //             costCenterItem.name = '';
        //             costCenterItem.costCenterOID = '';
        //           }
        //         });
        //       }
        //     });
        //   }
        // }
        if (expense.expenseType && expense.expenseType.apportionEnabled && !(expense.apportionmentDTOList && expense.apportionmentDTOList.length)) {
          isChange = true;
          expense.apportionmentDTOList = [];
          let item = {
            entityType: 1001,
            scale: 100,
            amount: expense.amount,
            defaultApportion : true,
            costCenterItems: JSON.parse(JSON.stringify(defaultApportion.costCenterItems))
          };
          expense.apportionmentDTOList.push(item);
        }
      });
      if (refreshAmount) {
        isChange = true;
        let amount = 0;
        expenseBudgetList.map(item => {
          amount += Number((item.amount * (item.actualCurrencyRate || 1)).toFixed(queryCurrencyPrecision(formDetail.currencyCode || company.baseCurrency)));
        });
        value.amount = amount;
        value.refreshAmount = false;
      }
      if (isChange) {
        value.budgetDetail = expenseBudgetList;
        this.setState({ value, expenseBudgetList },() => {
          this.onChange(this.state.value)
        });
      }
    }
  };

  //isNeedReCalculate是否需要重算分摊金额
  resetApportionList = (isNeedReCalculate) => {
    const { apportionList, defaultApportion } = this.state;
    let defaultApportionList = JSON.parse(JSON.stringify(defaultApportion));
    this.setState({apportionList: [defaultApportionList]}, () => {
      if (isNeedReCalculate) {
        this.reCalculateAllApportion();
      }
    });
  };

  /**
   *
   * @param e valueOID
   * @param all valueItem
   * @param index 分摊行的序号
   * @param type 1部门 0成本中心
   * @param costCenter 成本中心OID
   */
  checkedChange = (e, all, index, type, costCenter) => {
    const { apportionList } = this.state;
    let isChangeDepartment = false;
    let isChangeFatherCostCenter = false;
    let parentCostCenterOID = '';
    apportionList[index].costCenterItems.map(costCenterItem => {
      //处理分摊中部门更改
      if (costCenterItem.type === type && type === 1 && e !== costCenterItem.costCenterOID) {
        isChangeDepartment = true;
        if (e) {
          costCenterItem.costCenterOID = all.departmentOid;
          costCenterItem.name = (this.props.profile && this.props.profile['department.full.path.disabled']) ? all.name :
            all.path ? all.path : all.name;
          costCenterItem.pathDepth = all.path ? all.path.split('|').length : costCenterItem.pathDepth ? costCenterItem.pathDepth : 1;
        } else {
          costCenterItem.costCenterOID = '';
          costCenterItem.name = '';
          costCenterItem.pathDepth = 1;
        }
      }
      //处理分摊中成本中心更改
      if (costCenterItem.type === type && type === 0 && costCenterItem.costCenter === costCenter && costCenter && e !== costCenterItem.costCenterOID) {
        if (e) {
          costCenterItem.costCenterOID = all.costCenterItemOID;
          costCenterItem.name = all.name;
        } else {
          costCenterItem.costCenterOID = '';
          costCenterItem.name = '';
        }
        if (costCenterItem.costCenterType === 'father') {
          isChangeFatherCostCenter = true;
          parentCostCenterOID = costCenterItem.costCenterOID;
        }
      }
    });
    if (isChangeFatherCostCenter) {
      apportionList[index].costCenterItems.map(costCenterItem => {
        //处理子成本中心的parentCostCenterOID & 清空子成本中心项
        if (costCenterItem.type === 0 && costCenterItem.costCenterType === 'son') {
          costCenterItem.parentCostCenterOID = parentCostCenterOID;
          costCenterItem.costCenterOID = '';
          costCenterItem.name = '';
        }
      });
    }
    if (isChangeDepartment) {
      this.setState({tableLoading: true});
      requestService.checkCostCenterNeedEmpty().then(res => {
        //res.data为true说明要清空成本中心项
        if (res.data && res.data.visible) {
          apportionList[index].costCenterItems.map(costCenterItem => {
            //清空成本中心项
            if (costCenterItem.type === 0) {
              costCenterItem.costCenterOID = '';
              costCenterItem.name = '';
              if (costCenterItem.costCenterType === 'son') {
                costCenterItem.parentCostCenterOID = '';
              }
            }
          });
          this.setState({apportionList});
        }
      }).finally(() => {
        this.setState({tableLoading: false});
      });
    }
    this.setState({apportionList});
  };

  copyApportion = (tableIndex) => {
    const { apportionList } = this.state;
    let apportionItem = JSON.parse(JSON.stringify(apportionList[tableIndex]));
    apportionItem.amount = 0;
    apportionItem.scale = 0;
    apportionItem.defaultApportion = false;
    apportionItem.apportionmentOID = ''; //复制分摊行id要置空
    apportionItem.budgetCheckMessage = '';
    apportionItem.budgetLabelCode = '';
    apportionList.push(apportionItem);
    this.setState({apportionList});
  };

  deleteApportion = (tableIndex) => {
    const { apportionList } = this.state;
    apportionList.splice(tableIndex, 1);
    apportionList[0].amount = this.getDefaultAmountOrScale('amount', apportionList);
    apportionList[0].scale = this.getDefaultAmountOrScale('scale', apportionList);
    this.setState({apportionList});
  };

  handleNewExpenseApportion = () => {
    const { apportionList, apportionTemplate } = this.state;
    let apportionItem = JSON.parse(JSON.stringify(apportionTemplate));
    apportionList.push(apportionItem);
    this.setState({apportionList});
  };

  //按照比例重新计算分摊金额
  reCalculateAllApportion = () => {
    const { apportionList, isHasApportion, amount, currencyCode } = this.state;
    if (isHasApportion && apportionList.length) {
      let defaultAmount = amount;
      apportionList.map((oneApportion, index) => {
        //默认分摊另外处理
        if (index !== 0) {
          oneApportion.amount = Number((amount * oneApportion.scale / 100).toFixed(queryCurrencyPrecision(currencyCode)));
          defaultAmount -= oneApportion.amount;
        }
      });
      apportionList[0].amount = Number(Number(defaultAmount).toFixed(queryCurrencyPrecision(currencyCode)));
      this.setState({apportionList});
    }
  };

  /**
   *
   * @param value
   * @param type amount金额 scale比例
   * @param tableIndex 分摊行的序号
   */
  handleChangeAmountOrScale = (value, type, tableIndex) => {
    const { apportionList, amount, currencyCode } = this.state;
    if (!isNaN(value) && value !== null && value !== undefined && value !== '' && amount !== 0) {
      //修改金额
      if (type === 'amount') {
        let defaultAmount = amount;
        apportionList[tableIndex].amount = value;
        defaultAmount = this.getDefaultAmountOrScale('amount', apportionList);
        if (defaultAmount < 0) {
          apportionList[tableIndex].amount = 0;
          //重算默认分摊的金额
          apportionList[0].amount = this.getDefaultAmountOrScale('amount', apportionList);
        } else {
          apportionList[0].amount = defaultAmount;
        }
        //重算比例
        apportionList[tableIndex].scale = Number((apportionList[tableIndex].amount * 100 / amount).toFixed(2));
        apportionList[0].scale = this.getDefaultAmountOrScale('scale', apportionList);
        this.setState({apportionList});
      }
      //修改比例
      if (type === 'scale') {
        let defaultScale = 100;
        apportionList[tableIndex].scale = value;
        defaultScale = this.getDefaultAmountOrScale('scale', apportionList);
        if (defaultScale < 0) {
          apportionList[tableIndex].scale = 0;
          //重算默认分摊的比例
          apportionList[0].scale = this.getDefaultAmountOrScale('scale', apportionList);
        } else {
          apportionList[0].scale = defaultScale;
        }
        //重算金额
        apportionList[tableIndex].amount = Number((amount * apportionList[tableIndex].scale / 100).toFixed(queryCurrencyPrecision(currencyCode)));
        apportionList[0].amount = this.getDefaultAmountOrScale('amount', apportionList);
        this.setState({apportionList});
      }
    }
  };

  //计算默认分摊的金额或者比例
  /**
   *
   * @param type amount金额 scale比例
   * @param apportionList 分摊列表
   */
  getDefaultAmountOrScale = (type, apportionList) => {
    const { currencyCode } = this.state;
    let expenseAportionList = [];
    if (apportionList && apportionList.length) {
      expenseAportionList = apportionList;
    } else {
      expenseAportionList = this.state.apportionList;
    }
    let defaultAmount = this.state.amount;
    let defaultScale = 100;
    expenseAportionList.map((oneApportion, index) => {
      if (index !== 0) {
        defaultAmount -= oneApportion.amount;
        defaultScale -= oneApportion.scale;
      }
    });
    if (type === 'amount') {
      return Number(defaultAmount.toFixed(queryCurrencyPrecision(currencyCode)));
    }
    if (type === 'scale') {
      return Number(defaultScale.toFixed(2));
    }
  };

  showExpenseModal = (flag, record = {}, index) => {
    let isShowSelectExpense = true;
    if (!(record.apportionmentDTOList && record.apportionmentDTOList.length)) {
      this.resetApportionList();
      if (flag) {
        this.setState({isHasApportion: false});
      }
    } else {
      let apportionList = JSON.parse(JSON.stringify(record.apportionmentDTOList));
      this.setState({apportionList, isHasApportion: true});
    }
    if (flag && record && record.expenseType && record.expenseTypeOID) {
      record.expenseType.expenseTypeOID = record.expenseTypeOID;
      isShowSelectExpense = false;
    }
    if (!flag) {
      isShowSelectExpense = false;
    }
    let reimbursementTypeField = null;
    if (flag && record && record.dataReimbursementList && record.dataReimbursementList.length) {
      reimbursementTypeField = record.dataReimbursementList[0];
    }
    const {remarkPlaceholder, remarkTypes} = this.state;
    const expenseCode = record && record.expenseType && record.expenseType.code;
    this.setState({
      isShowSelectExpense,
      reimbursementTypeField,
      rowIndex: index,
      modalVisible: flag,
      uneditable: flag ? !!record.uneditable : false,
      amount: record.amount || 0,
      remark: flag ? record.remark : (remarkTypes.indexOf(expenseCode) > -1 ? messages(`mcd.placeholder.${expenseCode}`) : ''),
      remarkPlaceholder: remarkTypes.indexOf(expenseCode) > -1 ? messages(`mcd.placeholder.${expenseCode}`) : '',
      canSubmit: !!record.currencyCode,
      expenseChosenInfo: flag ? JSON.parse(JSON.stringify(record)) : {},
      paymentType: record.paymentType || 1001,
      currencyCode: record.currencyCode || this.props.company.baseCurrency,
      currencyName: record.currencyName || this.props.company.baseCurrencyName,
      actualCurrencyRate: record.actualCurrencyRate || 1,
      companyCurrencyRate: record.companyCurrencyRate || 1
    }, () => {
      if (flag) {
        //如果是新建预算明细，要重新初始化币种
        //如果是编辑预算明细，只需重新初始化isDisableCurrency
        this.initCurrency(this.props.copyValue, record.currencyCode);
      }
    });
  };

  //选择费用类型
  handleSelectExpenseType = (value) => {
    const baseCurrency = this.props.company.baseCurrency;
    const { currencyCode, amount, actualCurrencyRate, prohibitExchangeRateTol, paymentType, expenseChosenInfo: lastExpenseChosenInfo, remarkTypes } = this.state;
    let expenseChosenInfo = JSON.parse(JSON.stringify(lastExpenseChosenInfo));
    expenseChosenInfo.expenseType = value;
    let resultPaymentType = 1001;
    if (value.id) {
      if (lastExpenseChosenInfo.expenseType && lastExpenseChosenInfo.expenseType.expenseTypeOID) {
        //如果之前选择过费用类型，现在是切换费用类型，支付方式以之前用户勾选的为准
        resultPaymentType = paymentType;
      } else {
        //如果是第三方费用类型，或者是差补费用类型默认为公司支付
        resultPaymentType = (value.readonly || value.subsidyType === 1) ? 1002 : 1001;
      }
    }
    const remark = remarkTypes.indexOf(value.code) > -1 ? messages(`mcd.placeholder.${value.code}`) : '';
    this.setState({
      expenseChosenInfo,
      isShowSelectExpense: !value.id,
      isHasApportion: value.apportionEnabled === true,//根据费用上的字段来判断是否支持分摊
      paymentType: resultPaymentType,
      amount: value.id ? amount : 0,
      remark,
      remarkPlaceholder: remark,
      canSubmit: value.id && amount && (currencyCode === baseCurrency || (currencyCode !== baseCurrency && actualCurrencyRate < prohibitExchangeRateTol))
    }, () => {
      this.initExpenseField(value.id); //初始化费用上的控件中的报销类型控件
      this.resetApportionList(true);
    });
  };

  initExpenseField = (expenseId) => {
    if (expenseId) {
      let reimbursementTypeField = null;
      baseService.getExpenseTypeById(expenseId).then(res => {
        res.data && res.data.fields && res.data.fields.map(field => {
          if (field.messageKey === 'helios.reimbursement.type') {
            reimbursementTypeField = JSON.parse(JSON.stringify(field));
          }
        });
        this.setState({reimbursementTypeField});
      });
    }
  };

  //返回值列表控件所需的selectorItem
  getCustSelectorItem = () => {
    const { reimbursementTypeField } = this.state;
    let selectorItem = deepFullCopy(chooserData['multi_cust_list']);
    let OID = reimbursementTypeField.customEnumerationOID;
    selectorItem.title = reimbursementTypeField.name;
    selectorItem.url = `${config.baseUrl}/api/custom/enumerations/${OID}/items/v2`;
    return selectorItem;
  };

  //选择报销类型
  checkedCustChange = (e, all) => {
    let { reimbursementTypeField } = this.state;
    reimbursementTypeField.value = all ? all.value : '';
    reimbursementTypeField.showValue = all ? all.messageKey : '';
    this.setState({reimbursementTypeField});
  };

  handleRemarkChange = (value) => {
    if (value.length > 500) {
      message.error(messages('common.max.characters.length', {max: 500}));
    } else {
      this.setState({remark: value});
    }
  };

  //公司支付 or 个人支付
  handleCompanyPay = (e) => {
    this.setState({ paymentType: e.target.checked ? 1002 : 1001 })
  };

  //获取币种
  getCurrencyOptions = () => {
    const { jobInfo } = this.props;
    this.setState({ currencyFetching: true });
    (!this.state.currencyOptions.length || this.state.applicationOID !== this.props.user.userOID) && (
      baseService.getAllCurrencyByLanguage('zh_cn', this.props.formDetail.applicantOID || this.props.user.userOID, null, true, jobInfo.id).then(res => {
        let currencyOptions = [];
        //过滤掉禁用的企业币种
        res.data.map(item => {
          item.enable && currencyOptions.push(item)
        });
        this.setState({
          currencyOptions,
          currencyFetching: false,
          applicationOID: this.props.user.userOID
        })
      })
    );
    this.getRateDeviation()
  };

  //获取汇率
  getRate = () => {
    let date = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    requestService.getCurrencyRate(this.state.currencyCode, date, this.props.user.userOID, this.props.company.baseCurrency).then(res => {
      this.setState({
        rateDeviation: 0,
        actualCurrencyRate: Number(res.data.rate).toFixed(7),
        companyCurrencyRate: Number(res.data.rate).toFixed(7)
      })
    })
  };

  //获取汇率容差
  getRateDeviation = () => {
    baseService.getRateDeviation(this.props.tenantId, this.props.company.setOfBooksId).then(res => {
      this.setState({
        warnExchangeRateTol: res.data.warnExchangeRateTol || 10,
        prohibitExchangeRateTol: res.data.prohibitExchangeRateTol || 20
      })
    })
  };

  //选择币种
  handleCurrencyChange = (value) => {
    this.setState({ currencyCode: value },() => {
      this.setState({amount: currencyPrecisionCal(this.state.currencyCode, this.state.amount)}, () => {
        this.reCalculateAllApportion();
      });
      if (this.state.currencyCode !== this.props.company.baseCurrency) {
        this.getRate()
      } else {
        this.setState({
          actualCurrencyRate: 1, //汇率
          companyCurrencyRate: 1, //企业汇率
          rateDeviation: 0 //汇率偏移
        });
      }
    })
  };

  //修改金额
  handleAmountChange = (value, resetFlag) => {
    const baseCurrency = this.props.company.baseCurrency;
    const { currencyCode, rateDeviation, prohibitExchangeRateTol } = this.state;
    let canSubmit = value && (currencyCode === baseCurrency || (currencyCode !== baseCurrency && rateDeviation < prohibitExchangeRateTol));
    if (resetFlag || (!isNaN(value) && value !== null && value !== undefined && value !== '')) {
      this.setState({
        amount: value,
        canSubmit
      }, () => {
        this.reCalculateAllApportion();
      });
    }
  };

  //麦当劳要求 光标聚焦时清空金额
  handleFocus = () => {
    this.setState({
      amount: ''
    }, () => {
      this.handleAmountChange('', true);
    });
  };

  //修改汇率
  handleRateChange = (value) => {
    let rateDeviation = (Math.abs(value - this.state.companyCurrencyRate) / this.state.companyCurrencyRate * 100).toFixed(2);
    this.setState({
      actualCurrencyRate: value,
      rateDeviation,
      canSubmit: this.state.amount && rateDeviation < this.state.prohibitExchangeRateTol
    })
  };

  validateApportion = () => {
    const { apportionList } = this.state;
    let i = 0;
    for (i; i < apportionList.length; i++) {
      //判断分摊金额和分摊比例是否大于0
      if (!apportionList[i].amount || !apportionList[i].scale) {
        message.error(messages('request.key520')/*分摊金额和比例必须大于0*/);
        return false;
      }
      //判断分摊项是否有填, 校验部门必填，成本中心是否必填根据required字段判断，父成本中心有值，则子成本中心必填
      //判断分摊项是否有填时加一层校验，只在参与分摊的项中校验是否有填
      //如果分摊项都没有参与分摊，也要报错提示
      let j = 0;
      let isHasApportionItem;
      for(j; j < apportionList[i].costCenterItems.length; j++) {
        if (!apportionList[i].costCenterItems[j].costCenterOID
          && apportionList[i].costCenterItems[j].type === 1
          && apportionList[i].costCenterItems[j].isApportionItem) {
          message.error(messages('request.key521')/*有未填写的分摊项*/);
          return false;
        }
        if (!apportionList[i].costCenterItems[j].costCenterOID
          && apportionList[i].costCenterItems[j].type === 0
          && apportionList[i].costCenterItems[j].required
          && apportionList[i].costCenterItems[j].isApportionItem) {
          message.error(messages('request.key521')/*有未填写的分摊项*/);
          return false;
        }
        if (!apportionList[i].costCenterItems[j].costCenterOID
          && apportionList[i].costCenterItems[j].costCenterType === 'son'
          && apportionList[i].costCenterItems[j].parentCostCenterOID) {
          message.error(messages('common.please.select')/*请选择*/ + apportionList[i].costCenterItems[j].fieldName);
          return false;
        }
        if (apportionList[i].costCenterItems[j].isApportionItem) {
          isHasApportionItem = true;
        }
      }
      if (!isHasApportionItem) {
        message.error(messages('my-account.key81'/*费用分摊中的明细信息不完整，请完善*/));
        return false;
      }
    }
    return true;
  };

  //确定
  onSubmit = () => {
    const { isHasApportion, isShowSelectExpense, expenseChosenInfo } = this.state;
    //expenseChosenInfo.expenseType && expenseChosenInfo.expenseType.name
    if (isShowSelectExpense) {
      if (expenseChosenInfo.expenseType && expenseChosenInfo.expenseType.name) {
        this.setState({isShowSelectExpense: false});
      } else {
        message.error(messages('request.key557')/*请选择费用类型*/);
      }
      return;
    }
    if (!isHasApportion || (isHasApportion && this.validateApportion())) {
      this.onOk();
    }
  };

  //确定
  onOk = () => {
    const { formDetail, company } = this.props;
    let { rowIndex, expenseChosenInfo, paymentType, currencyCode, amount, actualCurrencyRate, companyCurrencyRate, expenseBudgetList, rateDeviation, warnExchangeRateTol, prohibitExchangeRateTol } = this.state;
    let { apportionList, isHasApportion, isHidePaymentType, uneditable, reimbursementTypeField, remark } = this.state;
    let expenseType = {
      iconName: expenseChosenInfo.expenseType.iconName,
      name: expenseChosenInfo.expenseType.name,
      iconURL: expenseChosenInfo.expenseType.iconURL
    };
    if (reimbursementTypeField && reimbursementTypeField.required && !reimbursementTypeField.value) {
      message.error(messages('request.key617',{arg1: reimbursementTypeField.name})/*请选择{arg1}*/);
      return;
    }
    this.props.form.validateFieldsAndScroll(err => {
      if (!err) {
        let values ={
          expenseType,
          uneditable,
          expenseTypeOID: expenseChosenInfo.expenseType.expenseTypeOID || expenseChosenInfo.expenseTypeOID,
          iconName: expenseChosenInfo.expenseType.iconName,
          iconURL: expenseChosenInfo.expenseType.iconURL,
          budgetLabelCode: expenseChosenInfo.budgetLabelCode,
          paymentType: isHidePaymentType ? 1001 : paymentType,
          currencyCode,
          amount,
          remark,
          baseCurrencyAmount: Number(amount * actualCurrencyRate).toFixed(queryCurrencyPrecision(formDetail.currencyCode || company.baseCurrency)),
          actualCurrencyRate: actualCurrencyRate || 1,
          companyCurrencyRate: companyCurrencyRate || 1,
          updateRate: true,     // 汇率是否可以更新
          rateProhibit: false,  // 汇率容差是否超出最大值
          rateWarning: false,   // 汇率容差是否警告
          ratePercentage: rateDeviation
        };
        //如果有报销类型，则赋值
        if (reimbursementTypeField) {
          values.dataReimbursementList = [{
            customEnumerationOID: reimbursementTypeField.customEnumerationOID,
            showValue: reimbursementTypeField.showValue,
            value: reimbursementTypeField.value,
            name: reimbursementTypeField.name,
            required: reimbursementTypeField.required,
            messageKey: reimbursementTypeField.messageKey,
            showOnList: reimbursementTypeField.showOnList
          }];
        }
        //如果是编辑预算明细，一些id要copy
        if (rowIndex || rowIndex === 0) {
          values.itineraryType = expenseBudgetList[rowIndex].itineraryType;
          values.budgetOID = expenseBudgetList[rowIndex].budgetOID;
          values.itinerarySummary = expenseBudgetList[rowIndex].itinerarySummary;
          values.itineraryOID = expenseBudgetList[rowIndex].itineraryOID;
          values.itineraryDirection = expenseBudgetList[rowIndex].itineraryDirection;
        }
        if (isHasApportion) {
          values.apportionmentDTOList = JSON.parse(JSON.stringify(apportionList));
        }
        if (rateDeviation >= prohibitExchangeRateTol) {
          values.rateProhibit = true;
          values.rateWarning = false;
        } else if (rateDeviation >= warnExchangeRateTol) {
          values.rateProhibit = false;
          values.rateWarning = true;
        } else {
          values.rateProhibit = false;
          values.rateWarning = false;
        }
        if (rowIndex || rowIndex === 0) {
          expenseBudgetList.map((item, index) => {
            index === rowIndex && (expenseBudgetList[index] = values)
          })
        } else {
          expenseBudgetList.push(values)
        }
        let value = this.state.value;
        if (expenseBudgetList.length) {
          let amount = 0;
          expenseBudgetList.map(item => {
            amount += Number((item.amount * (item.actualCurrencyRate || 1)).toFixed(queryCurrencyPrecision(formDetail.currencyCode || company.baseCurrency)));
          });
          value = {
            budgetDetail: [],
            amount: 0
          }
          value.budgetDetail = expenseBudgetList;
          value.amount = amount
        } else {
          value = undefined
        }
        this.setState({ value, expenseBudgetList },() => {
          this.showExpenseModal(false);
          this.onChange(this.state.value)
        })
      }
    })
  };

  //删除
  deleteExpenseType = (e, index) => {
    const { formDetail, company } = this.props;
    let { expenseBudgetList, deletedBudgetOIDList, value } = this.state;
    let deleteItem = JSON.parse(JSON.stringify(expenseBudgetList[index]));
    if (deleteItem.itineraryOID && deleteItem.budgetOID) {
      deletedBudgetOIDList.push(deleteItem.budgetOID);
    }
    expenseBudgetList.splice(index, 1);
    if (expenseBudgetList.length) {
      let amount = 0;
      expenseBudgetList.map(item => {
        amount += Number((item.amount * (item.actualCurrencyRate || 1)).toFixed(queryCurrencyPrecision(formDetail.currencyCode || company.baseCurrency)));
      });
      value = {
        budgetDetail: [],
        amount: 0
      }
      value.budgetDetail = expenseBudgetList
      value.amount = amount
      value.deletedBudgetOIDList = deletedBudgetOIDList.length ? deletedBudgetOIDList : [];
    } else {
      // value = {
      //   amount: 0,
      //   budgetDetail: []
      // }
      value = undefined;
      expenseBudgetList = [];
    }
    this.setState({ value, expenseBudgetList, deletedBudgetOIDList },() => {
      this.onChange(this.state.value);
    })
  };

  onChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
    }
  };

  expandedRowRender = (record) => {
    let expandedFlag = false;
    if (record.budgetLabelCode === 'BUD_002' || record.budgetLabelCode === 'BUD_003') {
      expandedFlag = true
    }
    return expandedFlag ? (
      <div className="expanded-row">
        {record.budgetLabelCode === 'BUD_002' && <div style={{color: '#FF0000'}}>{messages('request.key522')/*标签：超预算*/}</div>}
        {record.budgetLabelCode === 'BUD_003' && <div className='default-color-font'>{messages('request.key554')/*标签：预算预警*/}</div>}
      </div>
    ) : null;
  };

  //切换是否展示费用类型选择区域
  changeMode = () => {
    let { isShowSelectExpense } = this.state;
    this.setState({isShowSelectExpense: !isShowSelectExpense});
  };

  render() {
    const { formDetail, company, skinMode, fieldName } = this.props;
    const { modalVisible, currencyFetching, currencyOptions, expenseChosenInfo, canSubmit, currencyCode,currencyName, companyCurrencyRate, actualCurrencyRate, expenseBudgetList, columns, rateDeviation, warnExchangeRateTol, prohibitExchangeRateTol } = this.state;
    const { isHasApportion, apportionList, expenseApportionColumns, isDisableCurrency, amount, isShowSelectExpense,
      paymentType, isHidePaymentType, uneditable, reimbursementTypeField, remark, companyOID, tableLoading, remarkPlaceholder } = this.state;
    let totalAmount = 0;
    expenseBudgetList.map(item => {
      totalAmount += Number((item.amount * (item.actualCurrencyRate || 1)).toFixed(queryCurrencyPrecision(formDetail.currencyCode || company.baseCurrency)));
    });
    return (
      <div className="expense-type-modal">
        {skinMode === 'skin01' && (
          <div>
            <h3 className="header-title">{fieldName}</h3>
            {expenseBudgetList.length ? <Table rowKey={(record, index) => index}
                                               columns={columns}
                                               dataSource={expenseBudgetList}
                                               expandedRowRender={record => this.expandedRowRender(record)}
                                               rowClassName={record =>
                                                 (record.budgetLabelCode === 'BUD_002' || record.budgetLabelCode === 'BUD_003') ? '' : 'row-expand-display-none'}
                                               pagination={false}
                                               style={{width:'100%'}}
                                               onRow={(record, index) => ({
                                                 onClick:() => this.showExpenseModal(true, record, index)
                                               })}
                                               footer={() => {return(
                                                 <div style={{textAlign:'right',color:'#ff9900'}}>
                                                   {messages('request.key235'/*本币总金额*/)}：
                                                   <span style={{fontSize:20}}>
                                                       {formDetail.currencyCode || company.baseCurrency}
                                                     {this.filterMoney(totalAmount, queryCurrencyPrecision(formDetail.currencyCode || company.baseCurrency), true)}
                                                     </span>
                                                 </div>
                                               )}}
                                               bordered
                                               size="middle"/> : ''}
            <a onClick={() => this.showExpenseModal(true)}>
              <Icon type="plus-circle-o" className="add-budget-detail-icon"/>{messages('request.key236'/*添加费用类型及金额*/)}
            </a>
          </div>
        )}
        {!skinMode && (
          <div>
            {expenseBudgetList.length ? <Table rowKey={(record, index) => index}
                                               columns={columns}
                                               dataSource={expenseBudgetList}
                                               expandedRowRender={record => this.expandedRowRender(record)}
                                               rowClassName={record =>
                                                 (record.budgetLabelCode === 'BUD_002' || record.budgetLabelCode === 'BUD_003') ? '' : 'row-expand-display-none'}
                                               pagination={false}
                                               style={{width:'150%'}}
                                               onRow={(record, index) => ({
                                                 onClick:() => this.showExpenseModal(true, record, index)
                                               })}
                                               footer={() => {return(
                                                 <div style={{textAlign:'right',color:'#ff9900'}}>
                                                   {messages('request.key235'/*本币总金额*/)}：
                                                   <span style={{fontSize:20}}>
                                                       {formDetail.currencyCode || company.baseCurrency}
                                                     {this.filterMoney(totalAmount, queryCurrencyPrecision(formDetail.currencyCode || company.baseCurrency), true)}
                                                     </span>
                                                 </div>
                                               )}}
                                               bordered
                                               size="small"/> : ''}
            <a onClick={() => this.showExpenseModal(true)}>
              <Icon type="plus-circle-o" className="add-budget-detail-icon"/>{messages('request.key236'/*添加费用类型及金额*/)}
            </a>
          </div>
        )}

        <Modal title={messages('request.key236'/*添加费用类型及金额*/)}
               wrapClassName="expense-type-modal"
               width={720}
               footer={
                 <div>
                   <Button onClick={() => this.showExpenseModal(false)}>{messages('common.cancel')}</Button>
                   <Button type="primary" disabled={(!canSubmit && !isShowSelectExpense) || (remarkPlaceholder && !remark)} onClick={this.onSubmit}>{messages('common.ok')}</Button>
                 </div>
               }
               visible={modalVisible}
               onCancel={() => this.showExpenseModal(false)}>
          {expenseChosenInfo.expenseType && expenseChosenInfo.expenseType.name && !isShowSelectExpense && (
            <div className="expense-type-chosen">
              <div className="form-container">
                <Row>
                  <Col span={18}>
                    <Row>
                      <Col span={8} className="item-title">{messages('request.key237'/*已选类型*/)}: </Col>
                      <Col span={14} offset={1}>
                        <img src={expenseChosenInfo.expenseType.iconURL} onError={e => e.target.src = defaultExpenseTypeIcon} className="icon-img" />
                        <Popover content={expenseChosenInfo.expenseType.name}>
                          <span onClick={!uneditable && this.changeMode} className={`icon-name ${uneditable ? 'icon-disabled' : ''}`}>{expenseChosenInfo.expenseType.name}</span>
                        </Popover>
                      </Col>
                    </Row>
                  </Col>
                  {!isHidePaymentType && (
                    <Col span={6}>
                      <Row>
                        <Col span={22} offset={1}>
                          <Checkbox checked={paymentType === 1002} onChange={this.handleCompanyPay}>{messages('request.key233'/*公司支付*/)}</Checkbox>
                        </Col>
                      </Row>
                    </Col>
                  )}
                </Row>
                {formDetail.formType === 2001 && (
                  <Row className="currency-row">
                    <Col span={18}>
                      <Row style={{lineHeight: '31px'}}>
                        <Col span={8} className="item-title">{messages('request.key559')/*行程*/}: </Col>
                        <Col span={14} offset={1}>
                          {this.renderItineraryStr(expenseChosenInfo, false)}
                        </Col>
                      </Row>
                    </Col>
                  </Row>
                )}
                <Row className="currency-row">
                  <Col span={18}>
                    <Row>
                      <Col span={8} className="item-title required">{messages('request.key225'/*币种*/)}: </Col>
                      <Col span={14} offset={1}>
                        <Select dropdownMatchSelectWidth={false}
                                style={{width:'100%'}}
                                defaultValue={currencyCode || formDetail.currencyCode || this.props.company.baseCurrency}
                                disabled={isDisableCurrency || uneditable}
                                showSearch={true}
                                onFocus={this.getCurrencyOptions}
                                onChange={this.handleCurrencyChange}
                                optionFilterProp="children"
                                filterOption={(input, option) =>option.props.children.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                placeholder={messages('common.please.select')/* 请选择 */}>
                          {currencyOptions.map(item => {
                            return <Option key={item.currency}>{item.currency}{ this.props.language.code === 'zh_cn' ? ` ${item.currencyName}` : ''}</Option>
                          })}
                        </Select>
                      </Col>
                    </Row>
                  </Col>
                </Row>
                <Row className="currency-row">
                  <Col span={18}>
                    <Row>
                      <Col span={8} className="item-title required">{messages('request.key226'/*金额*/)}: </Col>
                      <Col span={14} offset={1}>
                        <InputNumber min={0}
                                     disabled={uneditable}
                                     precision={queryCurrencyPrecision(currencyCode)}
                                     step={1}
                                     defaultValue={expenseChosenInfo.amount || undefined}
                                     value={amount}
                                     placeholder={messages('common.please.enter')}
                                     formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                     style={{width:'100%'}}
                                     onFocus={this.handleFocus}
                                     onChange={this.handleAmountChange}/>
                      </Col>
                    </Row>
                  </Col>
                </Row>
                {reimbursementTypeField && reimbursementTypeField.showOnList && (
                  <Row className="currency-row">
                    <Col span={18}>
                      <Row>
                        <Col span={8} className={`item-title ${reimbursementTypeField.required ? 'required' : ''}`}>{reimbursementTypeField.name}: </Col>
                        <Col span={14} offset={1}>
                          <Chooser
                            selectorItem={this.getCustSelectorItem()}
                            valueKey="value"
                            labelKey="messageKey"
                            onlyNeed="value"
                            value={reimbursementTypeField.value ? [{messageKey: reimbursementTypeField.showValue, value: reimbursementTypeField.value}] : undefined}
                            onChange={(e, all) => this.checkedCustChange(e, all)}
                            single
                          />
                        </Col>
                      </Row>
                    </Col>
                  </Row>
                )}
                <Row className="currency-row">
                  <Col span={18}>
                    <Row>
                      <Col span={8} className={`item-title ${remarkPlaceholder ? 'required' : ''}`}>{messages('common.remark')/*备注*/}: </Col>
                      <Col span={14} offset={1}>
                        <TextArea
                          rows={4}
                          placeholder={messages('request.key623')/*最多输入500个字符*/}
                          style={{resize: 'none', fontSize: '12px'}}
                          value={remark}
                          onChange={e => this.handleRemarkChange(e.target.value)}
                        />
                      </Col>
                    </Row>
                  </Col>
                </Row>
                {currencyCode !== this.props.company.baseCurrency && this.props.formDetail.formType !== 2001
                && this.props.formDetail.formType !== 2002 && (
                  <Row className="rate-row">
                    <Col span={12}>
                      <Row>
                        <Col span={8} className="item-title required">{messages('request.key227'/*汇率*/)}: </Col>
                        <Col span={14} offset={1}>
                          <InputNumber size="small"
                                       min={0}
                                       precision={4}
                                       step={0.0001}
                                       value={actualCurrencyRate || 0}
                                       disabled={this.checkFunctionProfiles('web.expense.rate.edit.disabled', true)}
                                       style={{width:'100%'}}
                                       onChange={this.handleRateChange}/>
                        </Col>
                      </Row>
                    </Col>
                    <Col span={12} className="company-rate">
                      {messages('request.key228'/*企业汇率*/)}: <span>{companyCurrencyRate}</span>
                      {messages('request.key238'/*偏离*/)}: <span className={rateDeviation >= prohibitExchangeRateTol ? 'error' :
                      rateDeviation >= warnExchangeRateTol ? 'warning' : ''}>{rateDeviation}%</span>
                    </Col>
                  </Row>
                )}
              </div>
            </div>
          )}
          {isHasApportion && !isShowSelectExpense && (
            <div className="expense-type-container expense-type-container-small" style={{padding: '20px 40px'}}>
              <Table rowKey={(record, index) => index}
                     columns={expenseApportionColumns}
                     loading={tableLoading}
                     dataSource={apportionList}
                     pagination={false}
                     style={{width:'100%'}}
                     bordered
                     size="small"
                     footer={() => {return (
                       <div className="new-expense-apportion" onClick={this.handleNewExpenseApportion}>
                         <Icon type="plus"/>{messages('my-account.key23'/*新建分摊*/)}
                       </div>
                     )}}/>
            </div>
          )}
          {isShowSelectExpense && (
            <div className="expense-type-container">
              <ExpenseTypeSelector
                onSelect={this.handleSelectExpenseType}
                source="formV3"
                value={expenseChosenInfo.expenseType}
                param={{
                  companyOID,
                  formOID: this.props.formOID,
                  subsidyType: 99,
                  userOID: this.props.user.userOID,
                  setOfBooksId: this.props.formDetail.setOfBooksId
                }}
              />
            </div>
          )}
        </Modal>
      </div>
    )
  }
}

ExpenseTypeModal.propTypes = {
  formOID: React.PropTypes.string.isRequired, //表单OID
  formDetail: React.PropTypes.object.isRequired, //表单OID
  value: React.PropTypes.object,
  jobInfo: React.PropTypes.object, //岗位信息
  fieldName: React.PropTypes.string, //预算明细控件的fieldName
  skinMode: React.PropTypes.string, //展示的样式模式，undefined为默认样式，skin01为1号样式
  copyValue: React.PropTypes.array,
  onChange: React.PropTypes.func,  //进行选择后的回调
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    profile: state.login.profile,
    language: state.main.language,
    tenantId: state.login.company.tenantId
  }
}

const wrappedExpenseTypeModal = Form.create()(ExpenseTypeModal);

export default connect(mapStateToProps)(wrappedExpenseTypeModal)
